using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Text.RegularExpressions;


//XML stuff
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

//Summary
using NClassifier.Summarizer;
namespace TEILib
{
    /// <summary>
    /// Summary description for TEIDocument
    /// </summary>
    public class TEIDocument : XmlDocument
    {
        //Add a namespace manager to the document
        //private XmlNamespaceManager objNamespaceManager;

        #region Properties
        private string strFullFilePath;

        //The full path and file name of the file.
        public string FullFilePath
        {
            get { return strFullFilePath; }
            set { strFullFilePath = value; }
        }

        private string strFileName;

        //The file name of the file.
        public string FileName
        {
            get { return strFileName; }
            set { strFileName = value; }
        }

        private string strIdno;

        //The TEI idno for the document.
        public string idno
        {
            get { return strIdno; }
            set { strIdno = value; }
        }

        private string strTitle;

        //The TEI title of the document.
        public string title
        {
            get { return strTitle; }
            set { strTitle = value; }
        }

        //The TEI authors of the document.
        private ArrayList arrAuthor = new ArrayList();
        public ArrayList author
        {
            get { return arrAuthor; }
            set { arrAuthor = value; }
        }


        private ArrayList arrEditor = new ArrayList();
        /// <summary>
        /// The TEI editors of the document.
        /// </summary>
        public ArrayList editor
        {
            get { return arrEditor; }
            set { arrEditor = value; }
        }

        private XmlNamespaceManager objNamespaceManager;
        ///<summary>
        ///The TEI namespace used in the document.
        ///</summary>
        public XmlNamespaceManager NamespaceManager
        {
            get { return objNamespaceManager; }
            set { objNamespaceManager = value; }
        }

        private string _status;
        /// <summary>
        /// The status of processing the TEIDocument object.
        /// </summary>
        public string Status
        {
            get { return _status; }
            set { _status = value; }
        }
        #endregion

        #region Constructor
        public TEIDocument()
        {
            //Default Constructor

            //Manage the namespace here
            objNamespaceManager = new XmlNamespaceManager(this.NameTable);
            objNamespaceManager.AddNamespace("tei", "http://www.tei-c.org/ns/1.0");
            this.NamespaceManager = objNamespaceManager;
        }
        public TEIDocument(string DocumentPath)
        {
            //Manage the namespace here
            objNamespaceManager = new XmlNamespaceManager(this.NameTable);
            objNamespaceManager.AddNamespace("tei", "http://www.tei-c.org/ns/1.0");
            this.NamespaceManager = objNamespaceManager;

            this.Load(DocumentPath);
            this.FullFilePath = DocumentPath;
            this.FileName = System.IO.Path.GetFileName(this.FullFilePath);
            this.idno = FileName.Substring(0, FileName.Length - 4);

            //get the title from the TEI document--there is only one title
            title = getListOfElements("//tei:title")[0].ToString();

            //get the authors from the TEI document
            author = getListOfElements("//tei:author");

            //get the editor from the TEI document
            editor = getListOfElements("//tei:editor");

        }
        #endregion

        /// <summary>
        /// Make a simple summary of the document.
        /// </summary>
        /// <returns></returns>
        public string Summary()
        {
            SimpleSummarizer ss = new SimpleSummarizer();
            this.Status = "Summarizing " + this.strFileName;
            return ss.Summarize(this.ToText(), 5);
        }

        ///<summary>
        ///Gets a list of any given element(node) in the document and returns an array list of the
        ///InnerText property of the node.
        /// </summary>
        public ArrayList getListOfElements(string XPath)
        {
            ArrayList arrElements = new ArrayList();
            XmlNodeList objNodeList = this.SelectNodes(XPath, this.NamespaceManager);
            foreach (XmlNode xn in objNodeList)
            {
                arrElements.Add(xn.InnerText);
            }

            return arrElements;
        }

        public XmlNodeList getNodeList(string XPath)
        {
            try
            {
                XmlNodeList objNodeList = this.SelectNodes(XPath, this.NamespaceManager);
                return objNodeList;
            }
            catch (System.Xml.XPath.XPathException)
            {
                throw;
            }
        }

        /// <summary>
        /// Get a simple word frequency for a document.
        /// </summary>
        /// <returns>A Hashtable containing words as keys and the frequency as values.</returns>
        public Hashtable WordFrequency()
        {
            Hashtable kwHash = NClassifier.Utilities.GetWordFrequency(this.ToText());
            this.Status = "Getting word frequency for " + this.FileName;
            return kwHash;
        }

        /*
        public void GetKeyWords()
        {
            // load the Document
            //XPathDocument doc = new XPathDocument("C:\\Documents and Settings\\jporter\\My Documents\\xml\\00000001.xml");
            TEIDocument doc = new TEIDocument("C:\\Documents and Settings\\jporter\\My Documents\\xml\\00000001.xml");

            // retrieve the navigator
            XPathNavigator nav = doc.CreateNavigator();

            // move navigator cursor to root node of document
            nav.MoveToRoot();

            // recursively walk the nodes of the root node
            string strDocText = "";
            doc.WalkNode(nav, ref strDocText);
            Console.WriteLine(strDocText);

            //use this string to get a word count
            char[] delimiterChars = { ' ', ',', '.', ':', '\t', '\n', '\r', '-' };
            string[] arrString = strDocText.Split(delimiterChars);
            Console.WriteLine("Word Count:" + arrString.Length);

            //find the occurrences of each word.
            Console.WriteLine("Word Frequency");
            int count = 0;
            for (int i = 0; i < arrString.Length; i++)
            {
                //iterate through again
                count = 0;
                for (int j = 0; j < arrString.Length; j++)
                {
                    //compare the ith element to the jth element
                    if (arrString[i] == arrString[j])
                    {
                        count++;
                    }
                }
                Console.WriteLine("{0} {1}", arrString[i], count);
            }
        }
        */
        /// <summary>
        /// Transform the document using the given XSL document.
        /// </summary>
        /// <param name="XslPath"></param>
        /// <param name="result"></param>
        public void Transform(string XslPath, string result)
    {
        try
        {
            //load the Xml doc
            //XPathDocument myXPathDoc = new XPathDocument(this.FullFilePath);

            XslCompiledTransform XslTrans = new XslCompiledTransform();

            //load the Xsl 
            XslTrans.Load(XslPath);

            //create the output stream
            //XmlTextWriter myWriter = new XmlTextWriter(result, null);

            //do the actual transform of Xml
            XslTrans.Transform(this.FullFilePath, result + "//" + this.FileName);

            //myWriter.Close();

        }
        catch (Exception e)
        {
            throw new TEILibException("TEIDocument.Transform(string, string)", e);
            //Console.WriteLine("Exception: {0}", e.ToString());
        }
    }

        /// <summary>
        /// Return a plain text representation of the xml document.
        /// </summary>
        /// <returns></returns>
        public string ToText()
        {
            string TAG_PATTERN = "<.*?>";
            return Regex.Replace(this.OuterXml, TAG_PATTERN, " ");
        }

        /// <summary>
        /// Create a teiHeader to add to documents created.
        /// </summary>
        /// <param name="author"></param>
        /// <param name="title"></param>
        /// <param name="xmlDoc"></param>
        /// <returns></returns>
        public XmlElement getTeiHeader(ArrayList author, string title)
        {
            XmlElement objTeiHeader = this.CreateElement("teiHeader");
            XmlElement objFileDesc = this.CreateElement("fileDesc");
            XmlElement objTitleStmt = this.CreateElement("titleStmt");
            XmlElement objTitle = this.CreateElement("title");
            XmlElement objAuthor = this.CreateElement("author");
            XmlElement objPublicationStmt = this.CreateElement("publicationStmt");
            XmlElement objPubP = this.CreateElement("p");
            XmlElement objSourceDesc = this.CreateElement("sourceDesc");
            XmlElement objSourceP = this.CreateElement("p");

            objTeiHeader.AppendChild(objFileDesc);
            objFileDesc.AppendChild(objTitleStmt);
            objTitleStmt.AppendChild(objTitle);
            objTitleStmt.AppendChild(objAuthor);
            objFileDesc.AppendChild(objPublicationStmt);
            objPublicationStmt.AppendChild(objPubP);
            objFileDesc.AppendChild(objSourceDesc);
            objSourceDesc.AppendChild(objSourceP);

            //set the title and author
            objAuthor.InnerText = author[0].ToString();
            objTitle.InnerText = title;

            return objTeiHeader;
        }
        /// <summary>
        /// A recursive method to use in getting document statistics
        /// </summary>
        /// <param name="nav"></param>
        /// <param name="output"></param>
        public void WalkNode(XPathNavigator nav, ref string output)
        {
            // display the node information in a pretty format
            //DisplayNode(nav);
            //string val = "";
            if (nav.NodeType == XPathNodeType.Text)
            {
                //val = nav.Value;
                output = output + " " + nav.Value;
                //Console.WriteLine(nav.Value);
            }
            //Console.WriteLine("Name:{0} Type:{1} Value:{2}",
            //     nav.Name, nav.NodeType, val);

            // process child attribute nodes
            //if (nav.HasAttributes)
            //{
            //    // loop through all the attributes of the 
            //    // current node
            //    // and display them
            //    while (nav.MoveToNextAttribute())
            //        DisplayNode(nav);

            //    // move back to the parent element node of the
            //    // attribute nodes
            //    nav.MoveToParent();
            //}

            // process child element nodes
            if (nav.HasChildren)
            {
                // move to the first child of the 
                // current node
                nav.MoveToFirstChild();

                // recursively display the first child node
                // and its subnodes
                WalkNode(nav, ref output);

                // loop through the rest of the siblings
                // recursively
                while (nav.MoveToNext())
                    WalkNode(nav, ref output);

                // move back to the original parent node
                nav.MoveToParent();
            }
        }
        /******************************************************************************
        function: getTEIDocument
        description: Create a TEI document to work with
        input:
            xmlDoc: an XML document object.
        output: a minimal TEI document.
            getTEIDocument: The TEI document
        ******************************************************************************/
        //public TEIDocument(String strStyleSheet)
        //{
        //    //title
        //    XmlElement eleTitle = this.CreateElement("title");

        //    //author
        //    XmlElement eleAuthor = this.CreateElement("author");

        //    //title statement
        //    XmlElement eleTitleStmt = this.CreateElement("titleStmt");
        //    eleTitleStmt.AppendChild(eleTitle);
        //    eleTitleStmt.AppendChild(eleAuthor);

        //    //just a paragraph
        //    XmlElement eleP = this.CreateElement("p");

        //    //publication statment
        //    XmlElement elePublicationStmt = this.CreateElement("publicationStmt");
        //    elePublicationStmt.AppendChild(eleP);

        //    //just a(nother) paragraph
        //    /*Why recreate this--why doesn't it work if I don't*/
        //    eleP = this.CreateElement("p");

        //    //source description
        //    XmlElement eleSourceDesc = this.CreateElement("sourceDesc");
        //    eleSourceDesc.AppendChild(eleP);

        //    //compose the header element

        //    //file description
        //    XmlElement eleFileDesc = this.CreateElement("fileDesc");
        //    eleFileDesc.AppendChild(eleTitleStmt);
        //    eleFileDesc.AppendChild(elePublicationStmt);
        //    eleFileDesc.AppendChild(eleSourceDesc);

        //    //teiHeader
        //    XmlElement eleTeiHeader = this.CreateElement("teiHeader");
        //    eleTeiHeader.AppendChild(eleFileDesc);

        //    //make the body of the document

        //    //div
        //    XmlElement eleDiv = this.CreateElement("div");
        //    eleP = this.CreateElement("p");
        //    eleDiv.AppendChild(eleP);

        //    //body
        //    XmlElement eleBody = this.CreateElement("body");
        //    eleBody.AppendChild(eleDiv);

        //    //text
        //    XmlElement eleText = this.CreateElement("text");
        //    eleText.AppendChild(eleBody);

        //    //TEI.2
        //    XmlElement eleTEI2 = this.CreateElement("TEI.2");
        //    eleTEI2.AppendChild(eleTeiHeader);
        //    eleTEI2.AppendChild(eleText);

        //    XmlProcessingInstruction pi = this.CreateProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
        //    this.Load(pi.ToString()
        //        + strStyleSheet
        //        + "<!DOCTYPE TEI.2 PUBLIC '-//TEI P4//DTD Main Document Type//EN' 'http://www.tei-c.org/Lite/DTD/teixlite.dtd'>"
        //        + eleTEI2.ToString());

        //    return;
        //}

        /*
        1. Write a function spellcheck that returns an array. The first element
        will be the word to check. The subsequent elements will be the suggestions.
        This function should return an array of arrays. The subarrays will contain the word
        to check and suggestions. If the subarray contains only one element the word is spelled
        correctly or cannot be checked by the engine.

        2. Write a function that walks a XML document. It must split the document into
        single words. For example it can get the text of an element then the text can be
        easily split into an array of words. Each word can be spellchecked, then the correct
        word and suggestions can be returned if necessary.
        arrWords = eleXML.getText().split() //get the text into an array
        for each arrWords
            arrChecked = spellcheck(arrWords[i])
        next

        OR

        Can SAX2 be used and just walk through the document event-wise as suggested:

        start document
        start element: doc
        start element: para
        characters: Hello, world!
        end element: para
        end element: doc
        end document


        <myxml> 
        <p>You really think you are a good speler, don't you?</p> 
        </myxml> 


        var xmlDocument = new ActiveXObject('Msxml2.DOMDocument.3.0'); 
        xmlDocument.loadXML([ 
           '<myxml>', 
           '<p>You really think you are a good speler, don\'t you?</p>', 
           '</myxml>' 
        ].join('\r\n')); 
        xmlDocument.setProperty('SelectionLanguage', 'XPath'); 
        var p = xmlDocument.selectSingleNode('myxml/p'); 
        var currentChild = p.firstChild; 
        var newChild = currentChild.splitText(currentChild.data.indexOf('speler')); 
        newChild.splitText('speler'.length); 
        var newParent = xmlDocument.createElement('sp'); 
        newChild.parentNode.replaceChild(newParent, newChild); 
        newParent.appendChild(newChild); 
        var sug = xmlDocument.createElement('sug'); 
        sug.appendChild(xmlDocument.createTextNode('speller')); 
        newParent.appendChild(sug); 


        the XML markup (xmlDocument.xml) is now 


        <myxml> 
                <p>You really think you are a good <sp>speler<sug>speller</sug></sp>, 
        don't you?</p> 
        </myxml> 




        */

        /******************************************************************************
        function: getBibEntry
        description: get a single bibliographical entry from a given XML document
        input:
            strXmlDoc: the path to the xml document
        output:
            getBibEntry: the xml bibliogrpahic entry
        ******************************************************************************/
        public XmlNode getBibEntry()
        {
            //get the document id
            XmlElement objIdno = this.CreateElement("idno");
            objIdno.InnerText = this.idno;

            XmlElement objBibl = this.CreateElement("bibl");
            objBibl.AppendChild(objIdno);

            //get the titleStmt from the TEI document
            String strXPath = "//tei:titleStmt";
            XmlNode objNode = this.SelectSingleNode(strXPath, objNamespaceManager);

            foreach (XmlNode xn in objNode.ChildNodes)
            {
                //create a new node to work with
                XmlElement objElement = this.CreateElement(xn.Name);
                objElement.InnerText = xn.InnerText;
                objBibl.AppendChild(objElement);
                //Console.WriteLine(xn.InnerText);
            }

            //if the node is null make it not null
            if (objNode == null)
            {
                //objNode = new XmlElement();
                //objNode.InnerXml = "<title>Error: Not Found</title><author>Error: Not Found</author>";
            }
            //return objNode;
            return objBibl;
        }
        /******************************************************************************
        function: appendNodeList
        description: Append a node list to an element
        input:
            eleXML: A XML element.
            nodList: A node list.
        output:
            eleXML: The resulting XML element.
        ******************************************************************************/
        public XmlElement appendNodeList(XmlElement eleXML, XmlNodeList nodeList)
        {
            for (int i = 0; i < nodeList.Count; i++)
            {
                eleXML.AppendChild(nodeList.Item(i));
            }
            return (eleXML);
        }
        /******************************************************************************
        function: getNodeList
        description: Get a list of nodes from the given XML document.
        input:
            xmlDoc: A XML document object
            strXPath: A XPath string to select from the document.
        output:
            objNodeList: A list of nodes selected.
        ******************************************************************************/
        //public XmlNodeList getNodeList(XmlDocument xmlDoc, String strXPath)
        //{
        //    XmlNodeList objNodeList = new XmlNodeList();
        //    objNodeList = xmlDoc.DocumentElement.SelectNodes(strXPath);
        //    return objNodeList;
        //}
        /******************************************************************************
        function: getNode
        description: Get a node from the given XML document.
        input:
            xmlDoc: A XML document object
            strXPath: A XPath string to select from the document.
        output:
            objNode: A node 
        ******************************************************************************/
        //public XmlNode getNode(XmlDocument xmlDoc, String strXPath)
        //{
        //    //this.DocumentElement.SelectSingleNode(
        //    var objNode;
        //    objNode = xmlDoc.documentElement.selectSingleNode(strXPath);
        //    return objNode;
        //}

        /******************************************************************************
        function: xmlSpellcheck
        description: Check the spelling of an entire XML document.
        input:
            An XML document to check.
        output:
            A checked XML document to save to disk.
        ******************************************************************************/
        //public XmlElement xmlSpellcheck(String strXMLDoc)
        //{
        //XmlDocument xmlDoc = new XmlDocument();
        //var comment;
        //var root;
        //var arrText;
        //var arrWords;
        //var eleSpellList;
        //var eleItem;
        //xmlDoc.async = false;
        //xmlDoc.load(strXMLDoc);
        //if (xmlDoc.parseError.errorCode != 0)
        //{
        //   //var myErr = xmlDoc.parseError;
        //   //WScript.Echo("Error: " + myErr.reason);
        //}
        //else
        //{
        //    //create word object and add document
        //    //var objWord = new ActiveXObject("Word.Application");
        //    var objDoc = objWord.Documents.Add();

        //    eleList = xmlDoc.CreateElement("list");

        //    root = this.DocumentElement();
        //    for (int i=0; i<root.childNodes.length; i++)
        //    {
        //        //WScript.Echo(i);
        //        comment = root.childNodes.item(i);
        //        //WScript.Echo(comment.text);
        //        arrText = comment.text.split(" ");
        //        for(var j=0; j<arrText.length; j++)
        //        {
        //            arrWords = spellcheck(arrText[j], objWord);

        //            //eleList = xmlDoc.createElement("list");
        //            for(int k=0; k<arrWords.length; k++)
        //            {

        //                eleItem = this.CreateElement("item");
        //                eleItem.text = arrWords[k];
        //                attType = this.CreateAttribute("rend");

        //                if(k==0)
        //                {
        //                    attType.value = "suspect";
        //                }
        //                else
        //                {
        //                    attType.value = "suggestion";
        //                }
        //                eleItem.attributes.setNamedItem(attType);
        //                eleList.appendChild(eleItem);

        //                /*
        //                eleItem = xmlDoc.createElement("item");
        //                eleItem.text = arrWords[k];
        //                eleList.appendChild(eleItem);

        //                eleMainItem = xmlDoc.createElement("item");
        //                eleMainItem.appendChild(eleList);
        //                eleMainList.appendChild(eleMainItem);*/
        //            }
        //        }
        //    }
        //    objWord.Quit();
        //}
        //    XmlElement eleList = new XmlElement();
        //    return(eleList);
        //}
        /******************************************************************************
        function: teiLibrarySpellcheck
        description: spellcheck all the documents in a library and output a spellcheck
        document in TEI compliant form.
        input:
    
        output:
    
        ******************************************************************************/
        public void teiLibrarySpellcheck()
        {
            //var xmlDoc = new ActiveXObject("Msxml2.DOMDocument.3.0");
            //xmlDoc.resolveExternals = true;
            //xmlDoc.validateOnParse = false;
            //xmlDoc.async = false;

            ///*
            //var xmlDocOut = new ActiveXObject("Msxml2.DOMDocument.3.0");
            //xmlDocOut.resolveExternals = true;
            //xmlDocOut.validateOnParse = false;
            //xmlDocOut.async = false;
            //*/
            ////get the files in the library
            //arrFiles = getFiles("../xml");

            ////get a TEI document
            //xmlDoc = getTEIDocument(xmlDoc, "");

            ////get the div element
            //objNode = getNode(xmlDoc, "//text/body/div");

            ////create a list element
            //eleList2 = xmlDoc.createElement("list");

            ////spell check each document
            ////for(i = 0; i < arrFiles.length; i++)
            //for(var i = 0; i < 1; i++)
            //{
            //    //What document is being processed
            //    //WScript.Echo("Processing document: " + arrFiles[i]);

            //    //get the eleSpellList from each document
            //    eleSpellList = xmlSpellcheck("../xml/" + arrFiles[i]);

            //    //append the eleItem to eleList
            //    eleItem = xmlDoc.createElement("item");
            //    attID = xmlDoc.createAttribute("id");
            //    attID.value = "sp" + arrFiles[i];
            //    eleItem.attributes.setNamedItem(attID);
            //    eleItem.appendChild(eleSpellList);

            //    //append the eleItem to the eleList for persistence
            //    eleList2.appendChild(eleItem);
            //}

            ////append the eleList to the div element
            //objNode.appendChild(eleList2);

            ////save the document
            //xmlDoc.save("x:\\spellcheck.xml");

        }
        /******************************************************************************
        function: spellcheck
        description: Check the spelling of a single word and return the word and it's
        suggested spellings.
        input:
            strWord: A string to spell check
            objWord: An ActiveXObject for the Microsoft Word application.
        output:
            arrWords: An array of strings. The first element is the word to check.
            Subsequent elements are the suggestions, if necessary.
        ******************************************************************************/
        public void spellcheck(String strWord, String objWord)
        {
            //ArrayList arrWords = new Array();

            //if(!objWord.CheckSpelling(strWord))
            //{
            //    arrWords[0] = strWord;
            //    colSuggestions = objWord.GetSpellingSuggestions(strWord);

            //    for(int i = 1; i <= colSuggestions.count; i++)
            //    {
            //        arrWords[i] = colSuggestions.item(i);
            //    }
            //}

            //return arrWords;
        }

        /*
        function Main()
        {
            var arrFiles, strFileName;
            var xmlDocOut = new ActiveXObject("Msxml2.DOMDocument.3.0");
	
            strFileName = "Z:\\Documents\\EleList.xml";
	
            arrFiles = fileList("../xml").split(",");
	
            var xmlDocOut = new ActiveXObject("Msxml2.DOMDocument.3.0");
	
            //Create the list of Elements
            eleList = xmlDocOut.createElement("elementManifest");
	
            for(i = 0; i < arrFiles.length; i++)
            {
                WScript.Echo("Processing item " + (i + 1) + " of " + arrFiles.length);
                eleList.appendChild(getEleList(arrFiles[i], "//note"));
            }
	
            pi = xmlDocOut.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
            xmlDocOut.loadXML(pi.xml + "<?xml-stylesheet href='EleList.xsl' type='text/XSL'?>" 
                + eleList.xml);
	
            xmlDocOut.save(strFileName);
        }*/

        /*
        Function: getFigList
        Input:
            strXmlDoc: the path to the xml document
        Output:
            getEleList: the xml figure list
        */
        //public XmlElement getEleList(String strXmlDoc, String strEleSelect)
        //{
        //    String strFigEntry;
        //    XmlElement eleIdno = new XmlElement();
        //    XmlElement eleList = new XmlElement();
        //    XmlDocument xmlDocIn = new XmlDocument();
        //    XmlDocument xmlDocOut = new XmlDocument();
        //    xmlDocIn.Load("../xml/" + strXmlDoc);
        //    if (xmlDocIn.ParseError.errorCode != 0) 
        //    {
        //        //var myErr = xmlDocIn.parseError;
        //        //WScript.Echo("You have error " + myErr.reason);
        //    } 
        //    else 
        //    {
        //        eleList = xmlDocOut.CreateElement("eleList");

        //        /*Debug*/
        //        //WScript.Echo(eleList.xml);

        //        xmlDocIn.setProperty("SelectionLanguage", "XPath");

        //        //write the figure element
        //        objNodeList = xmlDocIn.documentElement.selectNodes(strEleSelect);	

        //        if(objNodeList.length > 0)
        //        {	

        //            //Write the id of the entry
        //            eleIdno = xmlDocOut.createElement("idno");
        //            eleIdno.text = strXmlDoc;
        //            eleList.appendChild(eleIdno);
        //        }

        //        for (int i = 0; i < objNodeList.length; i++)
        //        {
        //            eleList.appendChild(objNodeList.item(i));
        //        }

        //        /*Debug*/
        //        //WScript.Echo(eleFigList.xml);
        //        return eleList;
        //    }

        //}

        // JScript source code
        /*
        1. Write a function spellcheck that returns an array. The first element
        will be the word to check. The subsequent elements will be the suggestions.
        This function should return an array of arrays. The subarrays will contain the word
        to check and suggestions. If the subarray contains only one element the word is spelled
        correctly or cannot be checked by the engine.

        2. Write a function that walks a XML document. It must split the document into
        single words. For example it can get the text of an element then the text can be
        easily split into an array of words. Each word can be spellchecked, then the correct
        word and suggestions can be returned if necessary.
        arrWords = eleXML.getText().split() //get the text into an array
        for each arrWords
            arrChecked = spellcheck(arrWords[i])
        next

        OR

        Can SAX2 be used and just walk through the document event-wise as suggested:

        start document
        start element: doc
        start element: para
        characters: Hello, world!
        end element: para
        end element: doc
        end document


        <myxml> 
        <p>You really think you are a good speler, don't you?</p> 
        </myxml> 


        var xmlDocument = new ActiveXObject('Msxml2.DOMDocument.3.0'); 
        xmlDocument.loadXML([ 
           '<myxml>', 
           '<p>You really think you are a good speler, don\'t you?</p>', 
           '</myxml>' 
        ].join('\r\n')); 
        xmlDocument.setProperty('SelectionLanguage', 'XPath'); 
        var p = xmlDocument.selectSingleNode('myxml/p'); 
        var currentChild = p.firstChild; 
        var newChild = currentChild.splitText(currentChild.data.indexOf('speler')); 
        newChild.splitText('speler'.length); 
        var newParent = xmlDocument.createElement('sp'); 
        newChild.parentNode.replaceChild(newParent, newChild); 
        newParent.appendChild(newChild); 
        var sug = xmlDocument.createElement('sug'); 
        sug.appendChild(xmlDocument.createTextNode('speller')); 
        newParent.appendChild(sug); 


        the XML markup (xmlDocument.xml) is now 


        <myxml> 
                <p>You really think you are a good <sp>speler<sug>speller</sug></sp>, 
        don't you?</p> 
        </myxml> 




        */

        /******************************************************************************
        function: xmlSpellcheck
        description: Check the spelling of an entire XML document using SAX2.
        input:
            An XML document to check.
        output:
            A checked XML document to save to disk.
        ******************************************************************************/
        public void xmlSpellcheck()
        {
            ////WScript.Echo("Here!");
            //XmlDocument xmlDoc = new XmlDocument();
            //var comment;
            //var root;
            //var arrText;
            //var arrWords;
            //xmlDoc.async = false;
            //xmlDoc.load("../xml/00000001.xml");
            //if (xmlDoc.parseError.errorCode != 0)
            //{
            //   var myErr = xmlDoc.parseError;
            //   //WScript.Echo("Error: " + myErr.reason);
            //}
            //else
            //{
            //    //create word object and add document
            //    var objWord = new ActiveXObject("Word.Application");
            //    var objDoc = objWord.Documents.Add();

            //   root = xmlDoc.documentElement;
            //   for (int i=0; i<root.childNodes.length; i++)
            //   {
            //      //if (root.childNodes.item(i).nodeType == 8)
            //      //{
            //      //WScript.Echo(i);
            //         comment = root.childNodes.item(i);
            //         //WScript.Echo(comment.text);
            //         arrText = comment.text.split(" ");
            //         for(int j=0; j<arrText.length; j++)
            //         {
            //            arrWords = spellcheck(arrText[j], objWord);
            //            for(int k=0; k<arrWords.length; k++)
            //            {
            //                if(k==0)
            //                {
            //                    //WScript.Echo("<item>" + arrWords[k] + "</item>");
            //                }

            //            }
            //         }
            //      //}
            //   }
            //   objWord.Quit();
            //}
        }

        /******************************************************************************
        function: spellcheck
        description: Check the spelling of a single word and return the word and it's
        suggested spellings.
        input:
            strWord: A string to spell check
            objWord: An ActiveXObject for the Microsoft Word application.
        output:
            arrWords: An array of strings. The first element is the word to check.
            Subsequent elements are the suggestions, if necessary.
        ******************************************************************************/
        /*
        public void spellcheck(String strWord, String objWord)
    {
        var arrWords = new Array();
        //var objWord = new ActiveXObject("Word.Application");
        //var objDoc = objWord.Documents.Add();
        //var strInput;
        //do 
        //{
            //WScript.StdOut.Write("Please enter the word to be checked: "); 

        
            //strInput = WScript.StdIn.ReadLine();

            //WScript.Echo("strInput: " + strInput);

            if(!objWord.CheckSpelling(strWord))
            {

                arrWords[0] = strWord;
                colSuggestions = objWord.GetSpellingSuggestions(strWord);
            
                for(i = 1; i <= colSuggestions.count; i++)
                {

                    arrWords[i] = colSuggestions.item(i);
                }
            } 

        return arrWords;
    */
    }
}
